<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\App;
use think\facade\View;
use think\response\Json;

class ProductCate extends Base
{

    protected string $pk = 'id';

    protected string $validate = 'ProductCate';

    protected string $model = '\app\common\model\ProductCate';
    protected string $Productmodel = '\app\common\model\Product';

    protected int $writeLog = 2;


    public function index(): string
    {
        View::assign('list', $this->model::getAll());
        return View::fetch();
    }

    public function edit($id = '', $pid = '', $tpl = 'product_cate/edit'): string
    {
        $p_title = '';
        if ($pid) {
            $p_title = $this->model::where('id', $pid)->value('title');
        }

        View::assign('p_title', $p_title);
        View::assign('form', ['title' => '图标', 'field' => 'icon', 'value' => 1]);
        View::assign('formbg', ['title' => '分类背景图（750*150像素）', 'field' => 'bg', 'value' => 1]);
        return parent::edit($id, $tpl);
    }


    public function getCate(): \think\response\Json
    {
        $id = $this->request->param('id', 0);
        return json($this->model::getCate($id));
    }
    
    public function updateIsShow($key, $val, $id): Json
    {
        try {
            if ($val == 'true') $val = 1;
            if ($val == 'false') $val = 0;
            $this->model::update([$key => $val], ['id' => $id]);
            return json(['code' => 1, 'msg' => '操作成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }
    public function updateStatus($key, $val, $id): Json
    {
        try {
            if ($val == 'true') $val = 1;
            if ($val == 'false') $val = 0;
            $find=$this->model::find($id);
            if($find['pid']==0){
                $this->model::update([$key => $val], ['pid' => $id]);
                $this->Productmodel::update([$key => $val], ['cate_1' => $id]);
            }else{
                $pidfind=$find=$this->model::find($find['pid']);
                if($pidfind['status']==0){
                    return json(['code' => -1, 'msg' => '请开启一级分类！']);  
                }
            }
            $this->model::update([$key => $val], ['id' => $id]);
            $this->Productmodel::update([$key => $val], ['cate_2' => $id]);
            return json(['code' => 1, 'msg' => '操作成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

}
